import 'package:flutter/material.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/pages/main/vehicle_setting/helper.dart';
import 'package:inmotion_pro/pages/mixin/vehicle_type_mixin.dart';
import 'package:inmotion_pro/service/cache_config_service.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/service/realtime_data_server/realtime_data_polling_timer_helper.dart';
import 'package:inmotion_pro/service/realtime_data_server/vehicle_realtime_data/vehicle_settings.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'dart:async';
import '../../../config/const.dart';
import '../../../l10n/local.dart';
import '../../others/common_enum/riding_mode_type.dart';
import '../../mixin/cache_mixin.dart';
import '../../mixin/http_request_mixin.dart';
import '../../mixin/protocol_mixin.dart';
import '../../mixin/realtime_info_mixin.dart';
import '../../models/settting_item_model.dart';
import 'state.dart';

// 车辆设置控制器
class VehicleSettingController extends GetxController
    with
        HttpRequestMixin,
        CacheMixin,
        RealtimeInfoMixin,
        VehicleTypeMixin,
        ProtocolMixin {
  // 状态
  final VehicleSettingState state = VehicleSettingState();

  // 当前车辆类型
  VehicleType get _vehicleType => GlobalService.to.currentVehicleType;

  // 车辆昵称
  String _vehicleNickname = "";

  // 翘板速度
  RxDouble speedLimit = 0.0.obs;

  // 警告速度
  RxDouble warningSpeed = 0.0.obs;

  // 加速辅助
  RxDouble accAssist = 0.0.obs;

  // 刹车辅助
  RxDouble brakeAssist = 0.0.obs;

  // 踏板灵敏度
  RxDouble pedalSensitivity1 = 0.0.obs;
  RxDouble pedalSensitivity2 = 0.0.obs;

  // 平衡角度
  RxDouble balanceAngle = 0.0.obs;

  // 设置待机时长
  RxDouble standByTime = 0.0.obs;

  // 音量
  RxDouble volume = 0.0.obs;

  @override
  void onInit() {
    super.onInit();

    state.itemList.value = _vehicleType.getSettingItemList();

    // 延迟300毫秒，确保页面渲染完成后再监听变化
    Future.delayed(const Duration(milliseconds: 300), () {
      Future.wait<void>([
        // 监听车辆实时数据
        _refreshRealtimeData(),
        // 获取车辆昵称
        protocolMixinGetVehicleNickname().then((nickname) {
          _vehicleNickname =
              nickname.isEmpty ? defaultVehicleNickname : nickname;
          _refreshSettingItems(state.realtimeSetting.value);
        }),
      ]).catchErrorHandler();
    });
  }

  // 初始化车辆实时数据监听
  _refreshRealtimeData() {
    return realtimeInfoMixinStopLoopToGetVehicleRealTimeData()
        .then((_) => realtimeInfoMixinStartLoopToGetVehicleRealTimeData(
              pollingTypes: RealtimeDataPollingTimeHelper
                  .vehicleSettingPagePollingTypes,
              settingsCallback: (p0) {
                _refreshSettingItems(p0);
              },
            ));
  }

  // 刷新settings所有项
  void _refreshSettingItems(VehicleSettings settings) {
    GlobalService.to.realtimeSetting.value = settings;
    state.realtimeSetting.value = settings;
    // 优化：将需要设置的值提前缓存，减少重复计算
    final maxSpeedTiltBackSpeed =
        CacheConfigService.to.metricUnit(settings.limitSpeed / 100);
    final maxSpeedWarning = CacheConfigService.to
        .metricUnit(settings.limitSpeedWarningLevel1 / 100);
    final rideMode = _vehicleType.getRidingModeType(settings.rideMode);
    List<(RidingModeType, int)> ridingModeListObj =
        _vehicleType.getRidingModeList();
    List<RidingModeType> ridingModeList =
        ridingModeListObj.map((e) => e.$1).toList();
    List<int> ridingModeRawValueList =
        ridingModeListObj.map((e) => e.$2).toList();

    void setValue(SettingRowModel rowItem) {
      if (rowItem.title == local.vehicle_nickname) {
        // 车辆昵称
        rowItem.value = _vehicleNickname;
        rowItem.onTap = () {
          SettingHelper.instance.updateVehicleNicknameOnTap(
            _vehicleNickname,
            onSetCompleted: (p0) {
              _vehicleNickname = p0.isEmpty ? defaultVehicleNickname : p0;
              _refreshSettingItems(state.realtimeSetting.value);
            },
          );
        };
      } else if (rowItem.title == local.vehicle_password) {
        // 车辆密码
        rowItem.onTap = () {
          SettingHelper.instance.vehiclePasswordOnTap();
        };
      } else if (rowItem.title == local.max_speed_limit) {
        // 速度限速翘板
        speedLimit.value = maxSpeedTiltBackSpeed.$1;
        var unit = "${maxSpeedTiltBackSpeed.$2}/h";
        rowItem.value = "${speedLimit.value.round()} $unit";
        rowItem.onTap = () {
          LxBottomSheet.showSlider(
            Get.context!,
            title: rowItem.title,
            unit: unit,
            min: 0,
            max: _vehicleType.getMaxSpeedLimitByRidingMode(1) / 100.0,
            value: speedLimit,
            onChanged: (value) {
              speedLimit.value = value;
            },
            onChangeEnd: (value) {
              // 设置限速翘板，单位 0.01km/h
              SettingHelper.instance
                  .setSpeedLimitOnTap(value, warningSpeed.value,
                      onSetCompleted: (newLimitSpd, newWarnSpd) {
                _refreshRealtimeData();
              });
            },
          );
        };
      } else if (rowItem.title == local.max_speed_warning) {
        // 速度警告
        warningSpeed.value = maxSpeedWarning.$1;
        var unit = "${maxSpeedWarning.$2}/h";
        rowItem.value = "${warningSpeed.value.round()} $unit";
        var warnMaxSpd = _vehicleType.getMaxSpeedLimitByRidingMode(1) / 100.0;
        var max = speedLimit.value > warnMaxSpd ? warnMaxSpd : speedLimit.value;
        warningSpeed.value =
            warningSpeed.value > max ? max : warningSpeed.value;
        rowItem.onTap = () {
          LxBottomSheet.showSlider(
            Get.context!,
            title: rowItem.title,
            unit: unit,
            min: 0,
            max: max,
            value: warningSpeed,
            onChanged: (value) {
              warningSpeed.value = value;
            },
            onChangeEnd: (value) {
              // 设置报警速度，单位 0.01km/h
              SettingHelper.instance.setSpeedWarningOnTap(value,
                  onSetCompleted: (newValue) {
                _refreshRealtimeData();
              });
            },
          );
        };
      } else if (rowItem.title == local.riding_mode) {
        // 骑行模式
        rowItem.value = rideMode.name;
        rowItem.onTap = () {
          LxBottomSheet.show(
            Get.context!,
            title: rowItem.title,
            contentColor: Colors.white,
            selectIndex: ridingModeList.indexOf(rideMode),
            dataArr: ridingModeList.map((e) => e.name).toList(),
            cancelTitle: local.cancel,
            selectedCallback: (int index, String? selectedStr) {
              // 设置骑行模式
              SettingHelper.instance.setRidingModeOnTap(
                  ridingModeRawValueList[index], onSetCompleted: (newValue) {
                _refreshRealtimeData();
              });
            },
          );
        };
      } else if (rowItem.title == local.ride_assist) {
        // 骑行辅助
        rowItem.switchValue = settings.acceFeedback;
        rowItem.onChanged = (bool value) {
          SettingHelper.instance.setRideAssistOnTap(!settings.acceFeedback,
              onSetCompleted: (state) {
            _refreshRealtimeData();
          });
        };
      } else if (rowItem.title == local.acc_assist) {
        // 加速辅助
        accAssist.value = settings.speedingFeedback.roundToDouble();
        rowItem.value = "${settings.speedingFeedback.round()}%";
        rowItem.onTap = () {
          LxBottomSheet.showSlider(
            Get.context!,
            title: rowItem.title,
            unit: "%",
            min: 0,
            max: 100,
            value: accAssist,
            onChanged: (value) {
              accAssist.value = value;
            },
            onChangeEnd: (value) {
              // 设置加、减速辅助，单位 1%
              SettingHelper.instance.setAccAndBrakeAssistPercentageOnTap(
                  accAssist.value.round(), settings.brakingFeedback.round(),
                  onSetCompleted: (newValue1, newValue2) {
                _refreshRealtimeData();
              });
            },
          );
        };
      } else if (rowItem.title == local.brake_assist) {
        // 刹车辅助
        brakeAssist.value = settings.brakingFeedback.roundToDouble();
        rowItem.value = "${settings.brakingFeedback.round()}%";
        rowItem.onTap = () {
          LxBottomSheet.showSlider(
            Get.context!,
            title: rowItem.title,
            unit: "%",
            min: 0,
            max: 100,
            value: brakeAssist,
            onChanged: (value) {
              brakeAssist.value = value;
            },
            onChangeEnd: (value) {
              // 设置加、减速辅助，单位 1%
              SettingHelper.instance.setAccAndBrakeAssistPercentageOnTap(
                  settings.speedingFeedback.round(), brakeAssist.value.round(),
                  onSetCompleted: (newValue1, newValue2) {
                _refreshRealtimeData();
              });
            },
          );
        };
      } else if (rowItem.title == local.pedal_sensitivity) {
        // 判断当前骑行模式在 ridingModeList 中的位置
        int modeIndex = ridingModeList.indexOf(rideMode);
        if (modeIndex == 0) {
          // 第一个骑行模式，设置 sensitivity1
          pedalSensitivity1.value = settings.sensation1.roundToDouble();
          rowItem.value = "${settings.sensation1.round()}%";
          rowItem.onTap = () {
            LxBottomSheet.showSlider(
              Get.context!,
              title: rowItem.title,
              unit: "%",
              min: 0,
              max: 100,
              value: pedalSensitivity1,
              onChanged: (value) {
                pedalSensitivity1.value = value;
              },
              onChangeEnd: (value) {
                SettingHelper.instance.setPedalSensitivityOnTap(
                  pedalSensitivity1.value.round(),
                  settings.sensation2.round(),
                  onSetCompleted: (newValue1, newValue2) {
                    _refreshRealtimeData();
                  },
                );
              },
            );
          };
        } else {
          // 其他骑行模式，设置 sensitivity2
          pedalSensitivity2.value = settings.sensation2.roundToDouble();
          rowItem.value = "${settings.sensation2.round()}%";
          rowItem.onTap = () {
            LxBottomSheet.showSlider(
              Get.context!,
              title: rowItem.title,
              unit: "%",
              min: 0,
              max: 100,
              value: pedalSensitivity2,
              onChanged: (value) {
                pedalSensitivity2.value = value;
              },
              onChangeEnd: (value) {
                SettingHelper.instance.setPedalSensitivityOnTap(
                  settings.sensation1.round(),
                  pedalSensitivity2.value.round(),
                  onSetCompleted: (newValue1, newValue2) {
                    _refreshRealtimeData();
                  },
                );
              },
            );
          };
        }
      } else if (rowItem.title == local.balance_angle) {
        // 平衡角度
        balanceAngle.value = (settings.pitchZero / 100.0 > 10
                ? 10.0
                : (settings.pitchZero / 100.0 < -10
                    ? -10.0
                    : settings.pitchZero / 100.0))
            .roundToDouble();
        rowItem.value = "${(settings.pitchZero / 100).round()}°";
        rowItem.onTap = () {
          LxBottomSheet.showSlider(
            Get.context!,
            title: rowItem.title,
            unit: "°",
            min: -10,
            max: 10,
            value: balanceAngle,
            onChanged: (value) {
              balanceAngle.value = value;
            },
            onChangeEnd: (value) {
              // 设置平衡点
              SettingHelper.instance
                  .setBalanceZeroOnTap((balanceAngle.value * 100).round(),
                      onSetCompleted: (newValue) {
                _refreshRealtimeData();
              });
            },
          );
        };
      } else if (rowItem.title == local.berm_angle_mode) {
        // 赛道倾斜角模式
        rowItem.switchValue = settings.bermAngleMode;
        rowItem.onChanged = (bool value) {
          SettingHelper.instance.turnOnBermAngleMode(!settings.bermAngleMode,
              onSetCompleted: (state) {
            _refreshRealtimeData();
          });
        };
      } else if (rowItem.title == local.spin_kill) {
        // 防飞转
        rowItem.switchValue = settings.liftUpDetection;
        rowItem.onChanged = (bool value) {
          SettingHelper.instance.turnOnSpinKill(!settings.liftUpDetection,
              onSetCompleted: (state) {
            _refreshRealtimeData();
          });
        };
      } else if (rowItem.title == local.stand_by_time) {
        // 待机时间
        double maxTime = 60 * 4; // 最多4小时
        var val = (settings.standByTime / 60.0).roundToDouble();
        standByTime.value = val > maxTime ? maxTime : val;
        rowItem.value = "${(settings.standByTime / 60).round()} min";
        rowItem.onTap = () {
          LxBottomSheet.showSlider(
            Get.context!,
            title: rowItem.title,
            unit: "min",
            min: 0,
            max: maxTime, // 最多4小时
            value: standByTime,
            onChanged: (value) {
              standByTime.value = value;
            },
            onChangeEnd: (value) {
              // 设置待机时间，单位 秒
              SettingHelper.instance.setStandByTimeOnTap(
                  (standByTime.value * 60).round(), onSetCompleted: (newValue) {
                _refreshRealtimeData();
              });
            },
          );
        };
      } else if (rowItem.title == local.sound_wave) {
        // 声浪
        rowItem.switchValue = settings.activeSound;
        rowItem.onChanged = (bool value) {
          SettingHelper.instance.turnOnMainSound(!settings.activeSound,
              onSetCompleted: (state) {
            _refreshRealtimeData();
          });
        };
      } else if (rowItem.title == local.sound) {
        // 主音
        rowItem.switchValue = settings.audioSwitch;
        rowItem.onChanged = (bool value) {
          SettingHelper.instance.turnOnVoice(!settings.audioSwitch,
              onSetCompleted: (state) {
            _refreshRealtimeData();
          });
        };
      } else if (rowItem.title == local.volume) {
        // 音量
        volume.value = settings.voiceVolume.roundToDouble();
        rowItem.value = "${settings.voiceVolume}%";
        rowItem.onTap = () {
          LxBottomSheet.showSlider(
            Get.context!,
            title: rowItem.title,
            unit: "%",
            min: 0,
            max: 100,
            value: volume,
            onChanged: (value) {
              volume.value = value;
            },
            onChangeEnd: (value) {
              // 设置音量大小百分比
              SettingHelper.instance.setSoundVolumeOnTap(volume.value.round(),
                  onSetCompleted: (newValue) {
                _refreshRealtimeData();
              });
            },
          );
        };
      } else if (rowItem.title == local.tbox_charge) {
        // 云盒低电唤醒
        rowItem.switchValue = settings.tboxLowBatWakeUp;
        rowItem.onChanged = (bool value) {
          SettingHelper.instance.turnOnTBoxLowBatteryWakeupSwitchOnTap(
              !settings.tboxLowBatWakeUp, onSetCompleted: (state) {
            _refreshRealtimeData();
          });
        };
      } else if (rowItem.title == local.tbox_reboot) {
        // 重启云盒
        rowItem.onTap = () {
          SettingHelper.instance.rebootTboxOnTap();
        };
      } else if (rowItem.title == local.transport_mode) {
        // 运输模式
        rowItem.switchValue = settings.transportMode;
        rowItem.onChanged = (bool value) {
          SettingHelper.instance.turnOnTransportModeSwitchOnTap(
              !settings.transportMode, onSetCompleted: (state) {
            _refreshRealtimeData();
          });
        };
      } else if (rowItem.title == local.balance_calibration) {
        // 车辆平衡校正
        rowItem.onTap = () {
          SettingHelper.instance.vehicleBalanceCalibrationOnTap();
        };
      } else if (rowItem.title == local.turning_calibration) {
        // 车辆转向校正
        rowItem.onTap = () {
          SettingHelper.instance.vehicleTurningCalibrationOnTap();
        };
      } else if (rowItem.title == local.no_load_detect) {
        // 空载检测
      } else if (rowItem.title == local.motor_self_adjustment) {
        // 电机自适应
        rowItem.onTap = () {
          SettingHelper.instance.vehicleMotorAdaptationOnTap();
        };
      } else if (rowItem.title == local.auto_sleep) {
        // 自动熄屏
        rowItem.onTap = () {
          SettingHelper.instance.vehicleAutoSleepOnTap();
        };
      }
    }

    // 优化：使用递归方式遍历所有子项，减少嵌套循环
    void updateItems(List<SettingRowModel> items) {
      for (var rowItem in items) {
        setValue(rowItem);
        if (rowItem.subItems.isNotEmpty) {
          updateItems(rowItem.subItems);
        }
      }
    }

    for (var item in state.itemList) {
      updateItems(item.subItems);
    }
    state.itemList.refresh();
  }
}
